const express = require('express')
const router = express.Router()

/**
 * http://127.0.0.1/api/post/json
 *  ● { "name": "张智琦", "age": 18 }
 */
router.post('/post/json', express.json(), (req, res) => {
  res.send({
    status: 0,
    msg: '成功',
    data: req.body
  })
})

/**
 * http://127.0.0.1/api/post/x-www-form-urlencoded
 *  ● name  张智琦
 *  ● age   18
 */
router.post(
  '/post/x-www-form-urlencoded',
  express.urlencoded({ extended: false }),
  (req, res) => {
    res.send({
      status: 0,
      msg: '成功',
      data: req.body
    })
  }
)

const { dirPath, pathPrefix } = require('../config.js')
const multer = require('multer')
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, dirPath)
  },
  filename: (req, file, cb) => {
    let uniqueSuffix = Date.now().toString()
    let originalname = file.originalname
    if (originalname) {
      originalname = Buffer.from(originalname, 'latin1').toString('utf8')
      uniqueSuffix += ' ' + originalname
    }
    cb(null, uniqueSuffix)
  }
})
const upload = multer({ storage: storage })

/**
 * http://127.0.0.1/api/post/form-data
 *  ● name  张智琦
 *  ● age   18
 */
router.post('/post/form-data', upload.none(), (req, res) => {
  res.send({
    status: 0,
    msg: '成功',
    data: req.body
  })
})

/**
 * http://127.0.0.1/api/post/uploadFile
 *  ● file  <文件>
 */
router.post('/post/uploadFile', upload.single('file'), (req, res) => {
  req.body.file = undefined
  res.send({
    status: 0,
    msg: '成功',
    data: {
      ...req.body,
      url: `http://127.0.0.1${pathPrefix}/${req.file.filename}`
    }
  })
})

/**
 * http://127.0.0.1/api/post/uploadFiles
 *  ● files <文件>
 */
router.post('/post/uploadFiles', upload.array('files', 9), (req, res) => {
  req.body.files = undefined
  const urls = req.files.map(
    elem => `http://127.0.0.1${pathPrefix}/${elem.filename}`
  )
  res.send({
    status: 0,
    msg: '成功',
    data: {
      ...req.body,
      urls
    }
  })
})

module.exports = router
